from generate import MaimaiChartGenerator, generate_chart_from_features, generate_chart_with_audio_features
from chart_validator import ChartValidator
import random
import json
import os

def load_audio_features():
    """加载音频特征"""
    try:
        with open('features.json', 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print("未找到features.json文件，使用默认特征")
        return {
            "metadata": {
                "duration": 120.0,  # 默认2分钟
                "tempo": 120.0
            },
            "beats": [{"time": i * 0.5, "confidence": 0.8} for i in range(100)],  # 保持100个节拍
            "segments": [{"start": i * 2.0, "duration": 2.0, "pitches": [random.random() for _ in range(12)]} for i in range(25)]  # 保持原来的segment数量
        }

def load_maidata(file_path='maidata.txt'):
    """加载maidata.txt文件"""
    if not os.path.exists(file_path):
        print(f"未找到 {file_path} 文件")
        return None
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return content
    except Exception as e:
        print(f"读取 {file_path} 文件时出错: {e}")
        return None

def load_learning_patterns(file_path='incremental_learning_result.txt'):
    """加载学习到的谱面规律"""
    if not os.path.exists(file_path):
        print(f"未找到 {file_path} 文件，将使用默认生成策略")
        return None
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return content
    except Exception as e:
        print(f"读取 {file_path} 文件时出错: {e}")
        return None

def generate_chart_with_patterns(seed=None, pattern_knowledge=None):
    """
    基于学习到的规律和随机种子生成谱面
    
    Args:
        seed: 随机种子，用于控制生成的随机性
        pattern_knowledge: 学习到的谱面规律知识
    """
    if seed is not None:
        random.seed(seed)
    
    # 加载音频特征
    features = load_audio_features()
    
    # 获取音频时长
    duration = features.get("metadata", {}).get("duration", 120.0)
    
    # 生成谱面
    generator = generate_chart_with_audio_features(features, target_duration=duration)
    
    # 如果有学习到的规律知识，可以在这里应用
    # 目前作为示例，后续可以根据pattern_knowledge调整生成策略
    if pattern_knowledge:
        print("应用学习到的谱面规律...")
        # 这里可以根据学习到的规律调整生成器的参数
        # 例如调整音符类型权重、密度分布等
    
    # 生成谱面数据
    chart_data = generator.generate_chart_data()
    
    return chart_data

def main():
    # 检查maidata.txt文件是否存在
    maidata_content = load_maidata()
    
    if maidata_content:
        print("已加载 maidata.txt 文件")
        # 可以在这里添加对maidata.txt的处理逻辑
        # 例如验证谱面等
        
        # 验证生成的谱面
        print("正在验证谱面...")
        validator = ChartValidator()
        chart_lines = maidata_content.strip().split('\n')
        violations = validator.check_chart_violations(chart_lines)
        
        if violations:
            print(f"发现 {len(violations)} 个问题:")
            for i, violation in enumerate(violations):
                print(f"  {i+1}. {violation['message']}")
            
            # 尝试自动修复
            print("正在尝试自动修复...")
            fixed_chart_lines = validator.fix_chart(chart_lines)
            
            # 再次验证
            remaining_violations = validator.check_chart_violations(fixed_chart_lines)
            if remaining_violations:
                print(f"修复后仍存在 {len(remaining_violations)} 个问题:")
                for i, violation in enumerate(remaining_violations):
                    print(f"  {i+1}. {violation['message']}")
            else:
                print("所有问题已修复!")
        else:
            print("谱面验证通过，无问题发现!")
    else:
        print("未找到maidata.txt文件，使用基于学习规律的方式生成谱面...")
        
        # 加载学习到的规律
        pattern_knowledge = load_learning_patterns()
        
        # 使用固定种子生成可重现的谱面，或使用None以获得完全随机的谱面
        seed = 42  # 固定种子以确保可重现性，设为None可获得完全随机结果
        print(f"使用随机种子: {seed}")
        
        # 生成谱面
        chart_data = generate_chart_with_patterns(seed=seed, pattern_knowledge=pattern_knowledge)
        
        # 保存谱面到文件
        print("\n正在保存谱面...")
        with open('maidata.txt', 'w', encoding='utf-8') as f:
            for line in chart_data:
                f.write(line + '\n')
        print("谱面已生成并保存到 maidata.txt")
        
        # 验证生成的谱面
        print("正在验证生成的谱面...")
        validator = ChartValidator()
        chart_content = "\n".join(chart_data)
        violations = validator.check_chart_violations(chart_data)
        
        if violations:
            print(f"发现 {len(violations)} 个问题:")
            for i, violation in enumerate(violations):
                print(f"  {i+1}. {violation['message']}")
            
            # 尝试自动修复
            print("正在尝试自动修复...")
            fixed_chart_data = validator.fix_chart(chart_data)
            
            # 再次验证
            remaining_violations = validator.check_chart_violations(fixed_chart_data)
            if remaining_violations:
                print(f"修复后仍存在 {len(remaining_violations)} 个问题:")
                for i, violation in enumerate(remaining_violations):
                    print(f"  {i+1}. {violation['message']}")
            else:
                print("所有问题已修复!")
                # 保存修复后的谱面
                print("正在保存修复后的谱面...")
                with open('maidata.txt', 'w', encoding='utf-8') as f:
                    for line in fixed_chart_data:
                        f.write(line + '\n')
                print("修复后的谱面已保存到 maidata.txt")
        else:
            print("谱面验证通过，无问题发现!")

if __name__ == "__main__":
    main()